package com.ccys.common.util;


import cn.hutool.core.util.IdUtil;
import com.ccys.common.constants.ContextConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具
 *
 * @author Administrator
 * 时间戳转时间 https://tools.fun/timestamp.html
 */
@Component
public class JwtUtil {
    /**
     * token 过期时间, 单位: 毫秒. 这个值表示 30 天
     */
    //public static final Long TOKEN_EXPIRED_TIME = 30 * 24 * 60 * 60 * 1000L;
    public static final Long TOKEN_EXPIRED_TIME = ContextConstants.DEFAULT_PATIENT_EXPIRES_TIME ;
    /**
     * jwt 加密解密密钥(可自行填写) TODO
     */
    private static final String JWT_SECRET = "1234567890";//1234567890
    private static SecretKey secretKey = null;

    static {
        //签名秘钥，和生成的签名的秘钥一模一样
        byte[] encodedKey = Base64.getEncoder().encode(JWT_SECRET.getBytes());
        //在使用SecretKeySpec时，参数var4用于指定密钥的算法。这个参数应该填写对应的算法名称，例如"AES"、"DES"、"HmacSHA256"等等
        JwtUtil.secretKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    /**
     * 验证jwt
     *
     * @param jwtToken
     * @return
     */
    public static Claims verifyJwt(String jwtToken) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    //设置签名的秘钥
                    .setSigningKey(JwtUtil.secretKey)
                    .parseClaimsJws(jwtToken)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;

    }

    @Test
    public void JwtUtil() {
        Map<String, Object> payload = new HashMap<>();
        payload.put("id", "1111");
        String jwtToken = JwtUtil.createJwtToken(payload);
        System.out.println("加密串=" + jwtToken);
        System.out.println("解密串=" + JwtUtil.verifyJwt(jwtToken));
    }

    /**
     * 创建JWT
     *
     * @param payload
     * @return
     */
    public static String createJwtToken(Map<String, Object> payload) {
        return createJwtToken(payload, JwtUtil.TOKEN_EXPIRED_TIME);
    }

    /**
     * 创建JWT
     *
     * @param payload
     * @param timeOut 过期时间, 单位: 毫秒
     * @return
     */
    public static String createJwtToken(Map<String, Object> payload, long timeOut) {
        Date now = new Date();
        //下面就是在为payload添加各种标准声明和私有声明
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                //如果有私有声明，一定要先设置这个自己创建的私有的声明，这个是给builder的claim赋值，一旦写在标准的声明赋值之后，就是覆盖了那些标准的声明的
                .setClaims(payload)
                //设置jti(JWT ID)：是JWT的唯一标识，根据业务需要，这个可以设置为一个不重复的值，主要用来作为一次性token,从而回避重放攻击。
                //.setId(IdUtil.randomUUID())
                //iat: jwt的签发时间
                //.setIssuedAt(now)

                // 指定签名的时候使用的签名算法 设置签名使用的签名算法和签名使用的秘钥
                .signWith(SignatureAlgorithm.HS256, JwtUtil.secretKey);
        if (timeOut > 0) {
            long expMillis = now.getTime() + timeOut;
            Date exp = new Date(expMillis);
            //设置过期时间
            builder.setExpiration(exp);
        }
        return builder.compact();
    }

    @Test
    public  void testCreateJwtToken() {
        /**
         * {"role":"member","nameid":"uaMlnYDZvYBnSxKW3QIKF57xgaK37VikQSLBipzjD/ZIMzMwCeBkrkByVGdz2i7t",
         * "rfr-tkn":"62465991812127-6E9005DD-443A-4290-B2EA-F7F18DD8DDC7","request_update_contact_info":"False",
         * "request_activate_account":"False","for_child_that_turned_21":"False","device_id":"","device_type":"1",
         * "iss":"https://whcapi-qa.whitecoat.global/","aud":"414e1927a3884f68abc79f7283837fd1","exp":1737082696,"nbf":1705546696}
         */
        Map<String, Object> payload = new HashMap<>();
        payload.put("role", "member");
        payload.put("nameid","uaMlnYDZvYBnSxKW3QIKF57xgaK37VikQSLBipzjD/ZIMzMwCeBkrkByVGdz2i7t");

        payload.put("rfr-tkn","62465991812127-6E9005DD-443A-4290-B2EA-F7F18DD8DDC7");
        payload.put("request_update_contact_info","False");
        payload.put("request_activate_account","False");
        payload.put("for_child_that_turned_21","False");
        payload.put("device_id","");
        payload.put("device_type","1");
        payload.put("iss","https://whcapi-qa.whitecoat.global/");
        payload.put("aud","414e1927a3884f68abc79f7283837fd1");
        //到期时间戳秒
        payload.put("exp","1737082696");
        //当前时间戳秒
        payload.put("nbf","1705546696");

        String jwtToken = JwtUtil.createJwtToken(payload);
        System.out.println("加密串=" + jwtToken);
        System.out.println("解密串=" + JwtUtil.verifyJwt(jwtToken));
    }


}

